'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { ArrowLeft, FileText, Zap, Trash2, Download, Edit, Database } from 'lucide-react';
import toast from 'react-hot-toast';

interface KnowledgeBase {
  id: string;
  name: string;
  description: string;
  visibility: string;
  document_count: number;
  created_at: string;
  updated_at: string;
}

interface Document {
  id: string;
  title: string;
  file_name: string;
  file_size: number;
  file_type: string;
  is_vectorized: boolean;
  word_count: number;
  summary: string;
  upload_time: string;
  upload_user_name: string;
}

export default function KnowledgeBaseDetailPage() {
  const params = useParams();
  const router = useRouter();
  const kbId = params.id as string;
  
  const [knowledgeBase, setKnowledgeBase] = useState<KnowledgeBase | null>(null);
  const [documents, setDocuments] = useState<Document[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedDocIds, setSelectedDocIds] = useState<string[]>([]);
  const [deleteConfirm, setDeleteConfirm] = useState<{isOpen: boolean, docId: string, docTitle: string}>({
    isOpen: false,
    docId: '',
    docTitle: ''
  });

  useEffect(() => {
    loadKnowledgeBase();
    loadDocuments();
  }, [kbId]);

  const loadKnowledgeBase = async () => {
    try {
      const { knowledgeBaseApi } = await import('@/lib/api');
      // 注意：后端需要添加获取单个知识库详情的API
      const response = await knowledgeBaseApi.list();
      const kb = response.items?.find((k: any) => k.id === kbId);
      if (kb) {
        setKnowledgeBase(kb);
      } else {
        toast.error('知识库不存在');
        router.push('/dashboard/knowledge-base');
      }
    } catch (error: any) {
      console.error('加载知识库失败:', error);
      toast.error('加载知识库失败');
    }
  };

  const loadDocuments = async () => {
    setLoading(true);
    try {
      const { documentsApi } = await import('@/lib/api');
      const response = await documentsApi.list({
        page: 1,
        page_size: 100,
      });
      // 筛选属于当前知识库的文档
      const kbDocs = response.items?.filter((doc: any) => doc.knowledge_base_id === kbId) || [];
      setDocuments(kbDocs);
    } catch (error: any) {
      console.error('加载文档失败:', error);
      toast.error('加载文档失败');
    } finally {
      setLoading(false);
    }
  };

  const handleVectorize = async (docId: string, docTitle: string) => {
    try {
      const { documentsApi } = await import('@/lib/api');
      await documentsApi.vectorize(docId);
      toast.success(`${docTitle} 向量化成功`);
      loadDocuments();
    } catch (error: any) {
      toast.error('向量化失败: ' + (error.message || '未知错误'));
    }
  };

  const handleDeleteClick = (docId: string, docTitle: string) => {
    setDeleteConfirm({ isOpen: true, docId, docTitle });
  };

  const handleDeleteConfirm = async () => {
    const { docId } = deleteConfirm;
    try {
      const { documentsApi } = await import('@/lib/api');
      await documentsApi.delete(docId);
      toast.success('删除成功');
      loadDocuments();
      loadKnowledgeBase();
    } catch (error: any) {
      toast.error('删除失败: ' + (error.message || '未知错误'));
    }
  };

  const handleBatchVectorize = async () => {
    if (selectedDocIds.length === 0) {
      toast.error('请选择要向量化的文档');
      return;
    }
    
    try {
      const { documentsApi } = await import('@/lib/api');
      const result = await documentsApi.batchVectorize(selectedDocIds);
      toast.success(`成功向量化 ${result.succeeded} 个文档`);
      setSelectedDocIds([]);
      loadDocuments();
    } catch (error: any) {
      toast.error('批量向量化失败');
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (!knowledgeBase) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <Database className="h-16 w-16 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-500">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <GlassButton
          onClick={() => router.push('/dashboard/knowledge-base')}
          variant="secondary"
          size="sm"
        >
          <ArrowLeft className="h-4 w-4" />
        </GlassButton>
        <div className="flex-1">
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {knowledgeBase.name}
          </h1>
          {knowledgeBase.description && (
            <p className="text-gray-600 dark:text-white/70 mt-1">
              {knowledgeBase.description}
            </p>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <FileText className="h-8 w-8 text-indigo-500" />
            <div>
              <p className="text-sm text-gray-600 dark:text-white/70">文档数量</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {documents.length}
              </p>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <Zap className="h-8 w-8 text-green-500" />
            <div>
              <p className="text-sm text-gray-600 dark:text-white/70">已向量化</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {documents.filter(d => d.is_vectorized).length}
              </p>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <FileText className="h-8 w-8 text-orange-500" />
            <div>
              <p className="text-sm text-gray-600 dark:text-white/70">总字数</p>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">
                {documents.reduce((sum, d) => sum + (d.word_count || 0), 0).toLocaleString()}
              </p>
            </div>
          </div>
        </GlassCard>
      </div>

      {/* 批量操作工具栏 */}
      {selectedDocIds.length > 0 && (
        <GlassCard className="p-4 bg-indigo-50/80 dark:bg-indigo-900/20">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-indigo-900 dark:text-indigo-300">
              已选择 {selectedDocIds.length} 个文档
            </span>
            <div className="flex gap-2">
              <GlassButton
                onClick={handleBatchVectorize}
                variant="primary"
                size="sm"
              >
                <Zap className="mr-2 h-4 w-4" />
                批量向量化
              </GlassButton>
              <GlassButton
                onClick={() => setSelectedDocIds([])}
                variant="secondary"
                size="sm"
              >
                取消选择
              </GlassButton>
            </div>
          </div>
        </GlassCard>
      )}

      {/* Documents List */}
      <GlassCard className="p-6">
        <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
          文档列表
        </h2>
        <div className="space-y-3">
          {loading ? (
            <div className="text-center py-12 text-gray-500">
              加载中...
            </div>
          ) : documents.length === 0 ? (
            <div className="text-center py-12">
              <FileText className="h-16 w-16 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-500 dark:text-white/60">该知识库暂无文档</p>
              <GlassButton
                onClick={() => router.push('/dashboard/documents')}
                variant="primary"
                size="sm"
                className="mt-4"
              >
                前往上传文档
              </GlassButton>
            </div>
          ) : (
            documents.map((doc) => (
              <div
                key={doc.id}
                className="flex items-center justify-between p-4 rounded-lg bg-gray-100/50 dark:bg-white/5 hover:bg-gray-200/50 dark:hover:bg-white/10 transition-colors"
              >
                <div className="flex items-center gap-4 flex-1">
                  <input
                    type="checkbox"
                    checked={selectedDocIds.includes(doc.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedDocIds([...selectedDocIds, doc.id]);
                      } else {
                        setSelectedDocIds(selectedDocIds.filter(id => id !== doc.id));
                      }
                    }}
                    className="w-5 h-5 text-indigo-600 rounded border-gray-300"
                  />
                  <FileText className="h-10 w-10 text-indigo-500" />
                  <div className="flex-1">
                    <h3 className="text-gray-900 dark:text-white font-medium">{doc.title}</h3>
                    {doc.summary && (
                      <p className="text-sm text-gray-600 dark:text-white/60 mt-1 line-clamp-2">
                        {doc.summary}
                      </p>
                    )}
                    <div className="flex items-center gap-4 text-sm text-gray-600 dark:text-white/60 mt-2">
                      <span>{formatFileSize(doc.file_size)}</span>
                      <span>•</span>
                      <span>{doc.word_count || 0} 字</span>
                      <span>•</span>
                      <span>{doc.upload_user_name}</span>
                      <span>•</span>
                      <span>{formatDate(doc.upload_time)}</span>
                      {doc.is_vectorized && (
                        <>
                          <span>•</span>
                          <span className="text-green-500 font-medium">已向量化</span>
                        </>
                      )}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleVectorize(doc.id, doc.title)}
                    className={`p-2 rounded-lg transition-colors ${
                      doc.is_vectorized
                        ? 'hover:bg-green-100 dark:hover:bg-green-500/20 text-green-500'
                        : 'hover:bg-blue-100 dark:hover:bg-blue-500/20 text-blue-500'
                    }`}
                    title={doc.is_vectorized ? '重新向量化' : '向量化'}
                  >
                    <Zap className="h-5 w-5" />
                  </button>
                  <button
                    onClick={() => router.push(`/dashboard/documents`)}
                    className="p-2 rounded-lg hover:bg-indigo-100 dark:hover:bg-indigo-500/20 text-indigo-600"
                    title="编辑"
                  >
                    <Edit className="h-5 w-5" />
                  </button>
                  <button
                    onClick={() => handleDeleteClick(doc.id, doc.title)}
                    className="p-2 rounded-lg hover:bg-red-100 dark:hover:bg-red-500/20 text-red-600"
                    title="删除"
                  >
                    <Trash2 className="h-5 w-5" />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>
      </GlassCard>

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, docId: '', docTitle: '' })}
        onConfirm={handleDeleteConfirm}
        title="删除文档"
        message={`确定要删除文档"${deleteConfirm.docTitle}"吗？此操作不可恢复。`}
        confirmText="删除"
        cancelText="取消"
        variant="danger"
      />
    </div>
  );
}

